package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.CheckGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName ChcekGroupServiceImpl
 * @Description: TODO
 * @Author 郑乾
 * @Date 2020-06-21
 * @Version V1.0
 **/
@Service
public class ChcekGroupServiceImpl implements CheckGroupService {
    @Autowired
    CheckGroupDao checkGroupDao;

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //添加检查组
        checkGroupDao.add(checkGroup);
        //设置检查组和检查项的关系
        setCheckGroupAndCheckItems(checkGroup.getId(), checkitemIds);
    }

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page);
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroup(Integer id) {
        return checkGroupDao.findCheckItemIdsByCheckGroup(id);
    }

    @Override
    @Transactional
    public void edit(CheckGroup checkGroup, Integer[] checkItemIds) {
        //删除检查组和检查项的关联
        checkGroupDao.delCheckGroupAndCheckItems(checkGroup.getId());
        //维护新的关系
        setCheckGroupAndCheckItems(checkGroup.getId(), checkItemIds);
        //调用编辑方法
        checkGroupDao.edit(checkGroup);
    }

    @Override
    public void delById(Integer id) {
        long count = checkGroupDao.findCountById(id);
        if (count > 0) {
            throw new BusinessRuntimeException("该检查组被套餐所关联,无法删除");
        }
        checkGroupDao.delCheckGroupAndCheckItems(id);
        checkGroupDao.delById(id);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    private void setCheckGroupAndCheckItems(Integer checkGroupId, Integer[] checkitemIds) {
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                checkGroupDao.setCheckGroupWithCheckItems(checkGroupId, checkitemId);
            }
        }
    }
}
